package com.evan.review.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.evan.review.R;

/**
 * Fragment回退栈演示Activity
 * 用于展示Fragment事务的添加与回退栈管理
 */
public class BackStackActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "BackStackActivity";
    private TextView tvStackInfo;
    private TextView tvLifecycleLog;
    private int fragmentCounter = 0;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_back_stack);
        
        initViews();
        setupBackStackListener();
    }
    
    private void initViews() {
        tvStackInfo = findViewById(R.id.tv_stack_info);
        tvLifecycleLog = findViewById(R.id.tv_lifecycle_log);
        
        Button btnAddWithBackStack = findViewById(R.id.btn_add_with_back_stack);
        Button btnAddWithoutBackStack = findViewById(R.id.btn_add_without_back_stack);
        Button btnReplaceWithBackStack = findViewById(R.id.btn_replace_with_back_stack);
        Button btnReplaceWithoutBackStack = findViewById(R.id.btn_replace_without_back_stack);
        Button btnClearLog = findViewById(R.id.btn_clear_log);
        
        btnAddWithBackStack.setOnClickListener(this);
        btnAddWithoutBackStack.setOnClickListener(this);
        btnReplaceWithBackStack.setOnClickListener(this);
        btnReplaceWithoutBackStack.setOnClickListener(this);
        btnClearLog.setOnClickListener(this);
    }
    
    /**
     * 设置回退栈监听器
     */
    private void setupBackStackListener() {
        getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                updateBackStackInfo();
            }
        });
        
        // 初始化显示
        updateBackStackInfo();
    }
    
    /**
     * 更新回退栈信息
     */
    private void updateBackStackInfo() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        int backStackCount = fragmentManager.getBackStackEntryCount();
        
        StringBuilder sb = new StringBuilder();
        sb.append("当前回退栈中的条目数量: ").append(backStackCount).append("\n\n");
        
        if (backStackCount > 0) {
            sb.append("回退栈中的条目:\n");
            for (int i = 0; i < backStackCount; i++) {
                FragmentManager.BackStackEntry entry = fragmentManager.getBackStackEntryAt(i);
                sb.append(i).append(": ").append(entry.getName()).append("\n");
            }
        } else {
            sb.append("回退栈为空");
        }
        
        tvStackInfo.setText(sb.toString());
    }
    
    @Override
    public void onClick(View v) {
        int id = v.getId();
        
        if (id == R.id.btn_add_with_back_stack) {
            // 添加Fragment并加入回退栈
            addFragment(true);
        } else if (id == R.id.btn_add_without_back_stack) {
            // 添加Fragment但不加入回退栈
            addFragment(false);
        } else if (id == R.id.btn_replace_with_back_stack) {
            // 替换Fragment并加入回退栈
            replaceFragment(true);
        } else if (id == R.id.btn_replace_without_back_stack) {
            // 替换Fragment但不加入回退栈
            replaceFragment(false);
        } else if (id == R.id.btn_clear_log) {
            // 清空日志
            tvLifecycleLog.setText("");
            appendLog("日志已清空");
        }
    }
    
    /**
     * 添加Fragment
     */
    private void addFragment(boolean addToBackStack) {
        appendLog("添加Fragment" + (addToBackStack ? "(加入回退栈)" : "(不加入回退栈)"));
        
        // 创建Fragment
        fragmentCounter++;
        ColorFragment fragment = ColorFragment.newInstance(
                "Fragment " + fragmentCounter, 
                getRandomColor(), 
                fragmentCounter);
        
        // 设置回调
        fragment.setCallback(new ColorFragment.FragmentCallback() {
            @Override
            public void onFragmentEvent(String event) {
                appendLog(event);
            }
        });
        
        // 创建事务并添加Fragment
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fragment_container, fragment, "fragment_" + fragmentCounter);
        
        // 是否加入回退栈
        if (addToBackStack) {
            transaction.addToBackStack("add_" + fragmentCounter);
        }
        
        // 提交事务
        transaction.commit();
    }
    
    /**
     * 替换Fragment
     */
    private void replaceFragment(boolean addToBackStack) {
        appendLog("替换Fragment" + (addToBackStack ? "(加入回退栈)" : "(不加入回退栈)"));
        
        // 创建Fragment
        fragmentCounter++;
        ColorFragment fragment = ColorFragment.newInstance(
                "Fragment " + fragmentCounter, 
                getRandomColor(), 
                fragmentCounter);
        
        // 设置回调
        fragment.setCallback(new ColorFragment.FragmentCallback() {
            @Override
            public void onFragmentEvent(String event) {
                appendLog(event);
            }
        });
        
        // 创建事务并替换Fragment
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, fragment, "fragment_" + fragmentCounter);
        
        // 是否加入回退栈
        if (addToBackStack) {
            transaction.addToBackStack("replace_" + fragmentCounter);
        }
        
        // 提交事务
        transaction.commit();
    }
    
    /**
     * 生成随机颜色
     */
    private int getRandomColor() {
        int[] colors = {
                0xFFE57373, // 红色
                0xFF64B5F6, // 蓝色
                0xFF81C784, // 绿色
                0xFFFFD54F, // 黄色
                0xFFBA68C8, // 紫色
                0xFF4DB6AC, // 青色
                0xFFFF8A65  // 橙色
        };
        return colors[fragmentCounter % colors.length];
    }
    
    /**
     * 添加日志
     */
    private void appendLog(String log) {
        String currentLog = tvLifecycleLog.getText().toString();
        tvLifecycleLog.setText((currentLog.isEmpty() ? "" : currentLog + "\n") + log);
    }
    
    @Override
    public void onBackPressed() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        int backStackCount = fragmentManager.getBackStackEntryCount();
        
        if (backStackCount > 0) {
            appendLog("按下返回键: 弹出回退栈");
            fragmentManager.popBackStack();
        } else {
            appendLog("按下返回键: 回退栈为空，结束Activity");
            super.onBackPressed();
        }
    }
} 